import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:freemusic/components/InkWellContainer.dart';
import 'package:freemusic/model/AbstractSong.dart';
import 'package:freemusic/page/song/PlayPage.dart';
import 'package:freemusic/page/songsheet/SongSheetList.dart';
import 'package:freemusic/services/SongServices.dart';
import 'package:freemusic/utils/Util.dart';
import 'package:sticky_headers/sticky_headers.dart';

class SearchResult extends StatefulWidget {
  final String platform;
  final Duration duration;
  final List<AbstractSong> songs;
  final String keyword;

  SearchResult(this.platform, this.duration, {this.songs, this.keyword});

  @override
  State<StatefulWidget> createState() {
    return SearchState();
  }
}

class SearchState extends State<SearchResult> {
  bool _isExpanded = false;
  int count = 0;
  double _expandedHeight = 64.0;
  bool _loading = false;
  List<AbstractSong> songs;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  Widget renderHeader() {
    double screenWidth = MediaQuery.of(context).size.width;
    Color backgroundColor = Util.backgroundColor;
    return InkWell(
      onTap: () {
        this.setState(() {
          _isExpanded = !_isExpanded;
        });
        FocusScope.of(context).unfocus();
      },
      child: Container(
        width: screenWidth,
        padding: EdgeInsets.only(top: 8.0, bottom: 8.0),
        decoration: BoxDecoration(
          color: backgroundColor,
        ),
        child: Row(
          children: <Widget>[
            Icon(_isExpanded ? Icons.arrow_drop_down : Icons.arrow_right),
            Text(
              widget.platform,
              style: TextStyle(fontSize: 18),
            ),
          ],
        ),
      ),
    );
  }

  List<Widget> renderSongItem() {
    bool _isExpanded = this._isExpanded;
    List<Widget> list = List();
    songs = widget.songs;
    count = songs.length;
    if (_isExpanded) {
      songs.forEach((AbstractSong song) {
        list.add(SongItemWidget(song));
      });
      if (count > 0) {
        list.add(renderBottonAction());
      }
    }
    return list;
  }

  void _handleLoadOnTap() {
    this.setState(() {
      _loading = true;
    });
    String platform = widget.platform;
    int page = (count ~/ 10) + 1;
    String keyword = widget.keyword;
    SongServices.getInstace().searchByPage(platform, keyword, page).then((v) {
      this.setState(() {
        count = count + v;
        _loading = false;
      });
    });
  }

  Widget renderBottonAction() {
    Color color = Util.themeColor;
    bool _loading = this._loading;
    if (_loading) {
      return Container(
        margin: EdgeInsets.only(top: 16),
        child: SpinKitThreeBounce(
          color: color,
          size: 20.0,
        ),
      );
    } else {
      return GestureDetector(
        onTap: this._handleLoadOnTap,
        child: Container(
          padding: EdgeInsets.all(10),
          child: Text("点击加载更多"),
        ),
      );
    }
  }

  double mathHeight() {
    double _height = 0;
    int count = this.count;
    double _expandedHeight = this._expandedHeight;

    if (_isExpanded) {
      _height = (count + 1) * _expandedHeight;
    } else {
      _height = 0;
    }
    return _height;
  }

  @override
  Widget build(BuildContext context) {
    // double height = this.mathHeight();

    return StickyHeader(
      header: this.renderHeader(),
      content: Column(
          children: this.renderSongItem(),
        ),
    );
  }
}

class SongItemWidget extends StatelessWidget {
  final AbstractSong song;

  SongItemWidget(this.song);

  void handleMoreOnPressed(BuildContext context) {
    showModalBottomSheet(
        context: context,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(12),
            topRight: Radius.circular(12),
          ),
        ),
        builder: (context) {
          return _SongItemBottomSheet(
            song: song,
          );
        });
  }

  void handlerPlayMusic(BuildContext context) {
    SongServices.getInstace().playSong(song);
    Navigator.push(
        context, MaterialPageRoute(builder: (context) => PlayPage()));
  }

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {
        this.handlerPlayMusic(context);
      },
      child: Container(
        padding: EdgeInsets.all(8),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Expanded(
              child: Column(
                children: <Widget>[
                  Text(
                    song.songName, // item.songName,
                    style: TextStyle(
                      color: Color.fromRGBO(55, 55, 55, 1),
                      fontSize: 16.0,
                    ),
                    overflow: TextOverflow.ellipsis,
                  ),
                  Text(
                    song.singerName, // item.singerName,
                    style: TextStyle(color: Color.fromRGBO(120, 120, 120, 1)),
                  )
                ],
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
              ),
            ),
            IconButton(
              icon: Icon(
                Icons.more_vert,
                color: Colors.grey,
              ),
              onPressed: () {
                this.handleMoreOnPressed(context);
              },
            ),
          ],
        ),
      ),
    );
  }
}

class _SongItemBottomSheet extends StatelessWidget {
  final AbstractSong song;
  final double _iconSize = 24.0;

  const _SongItemBottomSheet({
    Key key,
    this.song,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    Color themeColor = Util.themeColor;

    return Container(
      height: 248,
      child: Column(
        children: <Widget>[
          Container(
            padding: EdgeInsets.only(top: 12, bottom: 12, left: 16, right: 16),
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                    width: 0.4, color: Color.fromRGBO(200, 200, 200, 1)),
              ),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                SongDetail(
                  singerName: song.singerName,
                  songName: song.songName,
                ),
                Column(
                  children: <Widget>[
                    Image.asset(
                      "images/${song.platform}.png",
                      width: 24,
                      height: 24,
                    ),
                    Text(
                      "来 源",
                      style: TextStyle(fontSize: 10),
                    )
                  ],
                ),
              ],
            ),
          ),
          Column(
            children: <Widget>[
              InkWellContainer(
                image: Image.asset(
                  "images/add-to-playlist.png",
                  width: _iconSize,
                ),
                text: "下一首播放",
                onTap: () {
                  SongServices.getInstace().addNextPlay(song);
                  Fluttertoast.showToast(
                    msg: "已添加到播放列表",
                  );
                },
              ),
              InkWellContainer(
                image: Icon(
                  Icons.add_box,
                  color: themeColor,
                ),
                text: "加到歌单",
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => SongSheetListPage(
                        waitAddSong: song,
                      ),
                    ),
                  );
                },
              ),
              InkWellContainer(
                image: Icon(
                  Icons.cloud_download,
                  color: themeColor,
                  size: _iconSize,
                ),
                text: "下载",
                onTap: () {
                  SongServices.getInstace().downloadSong(song);
                },
              ),
            ],
          )
        ],
      ),
    );
  }
}

class SongDetail extends StatelessWidget {
  final String songName;
  final String singerName;

  const SongDetail({Key key, this.songName, this.singerName}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    Color wordColor = Util.wordColor;
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Text(
          "$songName",
          style: TextStyle(
            fontSize: 16,
          ),
          overflow: TextOverflow.ellipsis,
        ),
        Text(
          "$singerName",
          style: TextStyle(fontSize: 14, color: wordColor),
          overflow: TextOverflow.ellipsis,
        ),
      ],
    );
  }
}
